package br.sc.senai.model.db;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import br.sc.senai.model.exception.DBException;
import br.sc.senai.model.resource.Mensagens;

/**
 * @author jefferson
 * */

public class ConnectionFactory {

	private String endereco = "jdbc:mysql://localhost:3306/locadora";
	private String usuario = "root";
	private String senha = "root";
	private String driver = "com.mysql.jdbc.Driver";
	private static ConnectionFactory connectionFactory;
	private Logger manageLog;

	public static ConnectionFactory getDBInstance() {
		if (connectionFactory == null)
			connectionFactory = new ConnectionFactory();
		return connectionFactory;
	}
	
	public Connection getConnection() throws DBException {
		Connection mConnection = null;
		try { 
			this.manageLog = Logger.getLogger(this.getClass().getName());
			
			Class.forName(driver);
			this.manageLog.log(Level.INFO, String.format("Driver: %s", driver));
			
			mConnection = DriverManager.getConnection(endereco, usuario, senha);
			this.manageLog.log(Level.INFO, "Conectado no banco!");
			return mConnection;
		} catch (SQLException e) {
			throw new DBException(String.format(Mensagens.ERRO_INESPERADO, "Conectar banco de dados."), e);
		} catch (ClassNotFoundException e) {
			throw new DBException(String.format(Mensagens.ERRO_INESPERADO, "Conectar banco de dados."), e);
		} 
	}

	public void desconectar(Connection pConnection) throws DBException {
		try {
			this.manageLog = Logger.getLogger(this.getClass().getName());
			if (pConnection != null && !pConnection.isClosed())
				pConnection.close();
			this.manageLog.log(Level.INFO, "Fechado conexão com banco de dados!");
		} catch (Exception e) {
			throw new DBException(String.format(Mensagens.ERRO_INESPERADO, "Desconectar banco de dados."), e);
		}
	}
}
